package main

import (
	"GoStreamVideoWebsite/api/session"
	"github.com/gin-gonic/gin"
	"net/http"
)

var (
	HEADER_FIELD_SESSION = "X-Session-Id" //X 开头表示自定义的头部，通过Add添加到http头部
	HEADER_FIELD_UNAME   = "X-User-Name"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		r := c.Request
		sid := r.Header.Get(HEADER_FIELD_SESSION)
		if len(sid) == 0 {
			c.Abort()
			return
		}
		uname, ok := session.IsSessionExpired(sid)
		if ok {
			c.Abort()
			return
		}
		r.Header.Add(HEADER_FIELD_UNAME, uname)
		c.Next()
	}
}

func validateUserSession(r *http.Request) bool {
	sid := r.Header.Get(HEADER_FIELD_SESSION)
	if len(sid) == 0 {
		return false
	}
	uname, ok := session.IsSessionExpired(sid)
	if ok {
		return false
	}
	r.Header.Add(HEADER_FIELD_UNAME, uname)
	return true
}

func ValidateUser(w http.Response, r *http.Request) bool {
	uname := r.Header.Get(HEADER_FIELD_UNAME)
	if len(uname) == 0 {
		//sendErrorResponse()
		return false
	}
	return true
}
